import hashlib
import time
import pymysql
import os
import yaml
import logging
import string
import random
import base64
from Crypto.Cipher import AES

# MD5加密
def sign_body(body,apikey="12345678"):
    a = ["".join(i) for i in body.items() if i[1]]
    strA = "".join(sorted(a))

    strsigntemp = strA + apikey
    src = strsigntemp.lower()
    m = hashlib.md5()
    m.update(src.encode("UTF-8"))
    md5_value = m.hexdigest()

    sign = md5_value
    body["sign"] = sign
    return body

# 链接数据库
class DbMysql(object):

    #初始化配置
    def __init__(self):
        self.db = pymysql.connect(
            cursorclass = pymysql.cursors.DictCursor,
            host = "49.235.92.12",
            port = 3309,
            user = "root",
            passwd = "123456",
            db = "apps"
        )
        self.cursor = self.db.cursor()

    def select_mysql(self,sql):
        #查询语句
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        return result

    def execute_mysql(self,sql):
        #新增、删除、修改语句
        self.cursor.execute(sql)
        self.db.commit()

    def close_mysql(self):
        #断开数据库连接
        self.cursor.close()
        self.db.close()

#获取根目录文件
def read_root_path(yaml_file_path,datas_path="datas"):
    path = os.path.dirname(os.path.realpath(__file__))
    root_path = os.path.dirname(path)
    read_path = os.path.join(root_path,datas_path,yaml_file_path)
    return read_path

#读取yaml文件内容
def read_yaml(yaml_path):
    open_yaml = open(yaml_path,"r",encoding="utf-8")
    yaml_open = open_yaml.read()
    yaml_list = yaml.safe_load(yaml_open)
    return yaml_list

#日志打印
def log_info(info):
    logger = logging.getLogger(__name__)
    logger.info(info)

#格式化获取当前时间
def new_time(time_date="%Y-%m-%d 00:00:00"):
    queryTime = time.strftime(time_date,time.localtime())
    return queryTime

#设置用例等待时间
def sleep(response, n_secs):
    if response.status_code == 200:
        time.sleep(n_secs)
    else:
        time.sleep(0.5)

# 读取文件内容
def get_file(file_name):
    root_path = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(root_path, "datas", file_name)
    return open(file_path, "rb")

#动态生成公共name
def random_name(realname="公共脚本名称",name_len=2):
    seeds = string.digits
    random_str = []
    for i in range(name_len):
        random_str.append(random.choice(seeds))
    name = realname + "".join((random_str))
    return name

#base64加密
def base64jiami(value):
    base64_pwd = str(base64.b64encode(value.encode("utf-8")))[2:-1]
    return base64_pwd

#sha256加密
def sha256jiami(value):
    s = hashlib.sha256()
    s.update(value.encode("utf-8"))
    b = s.hexdigest()
    return b

#md5加密
def md5jiami(value):
    s = hashlib.md5()
    s.update(value.encode("utf-8"))
    b = s.hexdigest()
    return b

#AES,ECB模式的加密
class EncryptDate:
    def __init__(self, key):
        self.key = key  # 初始化密钥
        self.length = AES.block_size  # 初始化数据块大小
        self.aes = AES.new(self.key, AES.MODE_ECB)  # 初始化AES,ECB模式的实例
        # 截断函数，去除填充的字符
        self.unpad = lambda date: date[0:-ord(date[-1])]

    def pad(self, text):
        """
        #填充函数，使被加密数据的字节码长度是block_size的整数倍
        """
        count = len(text.encode('utf-8'))
        add = self.length - (count % self.length)
        entext = text + (chr(add) * add)
        return entext

    def encrypt(self, encrData):  # 加密函数
        res = self.aes.encrypt(self.pad(encrData).encode("utf8"))
        msg = str(base64.b64encode(res), encoding="utf8")
        return msg

    # def decrypt(self, decrData):  # 解密函数
    #     res = base64.decodebytes(decrData.encode("utf8"))
    #     msg = self.aes.decrypt(res).decode("utf8")
    #     return self.unpad(msg)

def get_aes_pwd(password):
    # 这里密钥的长度必须是16的倍数 加密的时候需要的是二进制类型而不是文本类型，字符串前面加上b
    eg = EncryptDate(b"appkey")
    res = eg.encrypt(password)
    return res

if __name__ == '__main__':
   a = read_root_path(yaml_file_path="v1_goods_datas.yml")
   print(read_yaml(a))
   db = DbMysql()
   sql = 'select * from auth_user au where username = "test001"'
   result = db.select_mysql(sql)
   print(result)
   db.close_mysql()